#include "Scene.h"

OScene::OScene(QObject *parent) :
    BasicObject(parent)
{
    app = new OgreApplication();
    app->setObjectQueue(&objectQueue);
    app->setCmdQueue(&cmdQueue);
    app->setNodeQueue(&nodeQueue);

    m_Ared = m_AGreen = m_ABlue = 0.5;
    m_manager = 0;

    connect(this, SIGNAL(runSig()), app, SLOT(run()));
    connect(app, SIGNAL(ready(Ogre::SceneManager*)), this, SLOT(setManager(Ogre::SceneManager*)));
    connect(app, SIGNAL(frameRendered(int)), this, SIGNAL(onFrameRendered(int)));
    connect(app, SIGNAL(stopped()), this, SLOT(onStopped()));
    connect(app, SIGNAL(keyPress(int)), this, SIGNAL(onKeyPress(int)));

//    QVector<QObject*> v;
//    ONode* n = new ONode();
//    n->setId("n");
//    n->setParentNodeId("root");
//    v.append(n);
//    OEntity* e = new OEntity();
//    e->setId("ent");
//    e->setNodeId("n");
//    e->setModel("ogrehead.mesh");
//    v.append(e);
//    setObjects(v);

    run();
}

void OScene::onStopped()
{
    std::cerr << "\e[1;31mOScene exiting\e[m" << std::endl;
    delete app;
    deleteLater();
}

//  -------- property setters

void OScene::setARed(float c) {
    m_Ared = c;
    if (m_manager == 0) return;
    m_manager->setAmbientLight(Ogre::ColourValue(m_Ared, m_AGreen, m_ABlue));
}

void OScene::setAGreen(float c) {
    m_AGreen = c;
    if (m_manager == 0) return;
    m_manager->setAmbientLight(Ogre::ColourValue(m_Ared, m_AGreen, m_ABlue));
}

void OScene::setABlue(float c) {
    m_ABlue = c;
    if (m_manager == 0) return;
    m_manager->setAmbientLight(Ogre::ColourValue(m_Ared, m_AGreen, m_ABlue));
}

// -------------------------------------------

void OScene::run()
{
    app->moveToThread(&thread);
    thread.start();
    emit runSig();
}

void OScene::addObject(BasicObject *obj)
{
    qDebug() << "+++++ addObject :: " << obj->id() << " :: of type " << obj->type();
    if (obj->type() == NODE) {
        nodeQueue.append((ONode*)obj);
    } else {
        objectQueue.append(obj);
    }
}

void OScene::setManager(Ogre::SceneManager *manager)
{
    m_manager = manager;
    m_manager->setAmbientLight(Ogre::ColourValue(m_Ared, m_AGreen, m_ABlue));
    m_manager->setShadowTechnique(Ogre::SHADOWTYPE_TEXTURE_ADDITIVE);

    if (m_camId.length() > 0) {
        app->setMainCamera(m_manager->getCamera(m_camId.toStdString()));
    }
}

void OScene::stop()
{
    cmdQueue.append(STOP);
}

void OScene::pause()
{
    cmdQueue.append(PAUSE);
}

void OScene::resume()
{
    cmdQueue.append(RESUME);
}

OScene::~OScene(){
}
